package com.eventur;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource	;
import org.xml.sax.SAXException;


import android.text.TextUtils;
import android.util.Log;


public class XmlParser {

	public static ArrayList<Event> eventsList = null;
	public static NodeList eventsNodeList;
	public static int eventsNumber;
	private static Document document;
	private static InputStream inputStream;
	private String tag = "XmlParser";

	public static ArrayList<Event> todayEvents = null;
	public static ArrayList<Event> tomorrowEvents= null;
	public static ArrayList<Event> weekEvents= null;
	private static String tomorrow;
	private static SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
	private static DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
	private static Date todaysDate = new java.util.Date();
	
	public XmlParser(InputStream is){

		XmlParser.eventsList = new ArrayList<Event>();
		XmlParser.inputStream = is;
		XmlParser.eventsNodeList = null;
		XmlParser.todayEvents = new ArrayList<Event>();
		XmlParser.tomorrowEvents = new ArrayList<Event>();
		XmlParser.weekEvents = new ArrayList<Event>();


	}

	public int getEventsNumber(){
		return XmlParser.eventsNumber;
	}

	public ArrayList<Event> getEventsList(){
		return eventsList;
	}

	public int buildParser() {

		InputSource inputSource;
		try {
			inputSource = new InputSource(new InputStreamReader(XmlParser.inputStream));
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dom = factory.newDocumentBuilder();
			XmlParser.document = dom.parse(inputSource);
			XmlParser.eventsNodeList = XmlParser.document.getElementsByTagName("item");
			XmlParser.eventsNumber = XmlParser.eventsNodeList.getLength();
			Log.i(tag, "Size of eventsNodeList:"+XmlParser.eventsNumber);
		}

		catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();

		} catch (ParserConfigurationException e) {
			e.printStackTrace();

		} catch (SAXException e) {
			e.printStackTrace();

		}
		return 1;

	}

	public int parseEvents(int i){
		Event event = new Event() ;


		Node item = XmlParser.eventsNodeList.item(i);
		NodeList properties  = item.getChildNodes();


		for(int j =0; j< properties.getLength();j++){
			Node property = properties.item(j);
			if(property.getNodeType() == Node.ELEMENT_NODE){
				String name = property.getNodeName();
				//Log.i(tag,"property name"+name);

				if(name.equalsIgnoreCase("title")){
					try{
						event.setTitle(property.getFirstChild().getNodeValue());
						Log.i(tag,"title"+(property.getFirstChild().getNodeValue()));
					}
					catch(Exception e){
						Log.i(tag, "No title");
					}


				} else if(name.equalsIgnoreCase("link")) {
					try{
						event.setLink(property.getFirstChild().getNodeValue());
						Log.i(tag,"link"+(property.getFirstChild().getNodeValue()));
					}
					catch(Exception e){
						Log.i(tag, "No link");
					}


				} else if (property.getNodeName().equals("ens1:s_time")) {
					try{
						event.setsDate(property.getFirstChild().getNodeValue());
						Log.i(tag,"s_time"+(property.getFirstChild().getNodeValue()));
					}
					catch(Exception e){
						Log.i(tag, "No start time");
					}		
				} else if (property.getNodeName().equals("lat")) {
					try{
						event.setLatitude(property.getFirstChild().getNodeValue());
						Log.i(tag,"s_time"+(property.getFirstChild().getNodeValue()));
					}
					catch(Exception e){
						Log.i(tag, "No start time");
					}		
				} else if (property.getNodeName().equals("lon")) {
					try{
						event.setLongitude(property.getFirstChild().getNodeValue());
						Log.i(tag,"s_time"+(property.getFirstChild().getNodeValue()));
					}
					catch(Exception e){
						Log.i(tag, "No start time");
					}		
				} else if (property.getNodeName().equals("ens1:venue")){
					try{
						event.setVenue(property.getFirstChild().getNodeValue());
						Log.i(tag,"venue"+(property.getFirstChild().getNodeValue()));
					}
					catch(Exception e){
						Log.i(tag, "No venue");
					}

				} else if (property.getNodeName().equals("ens1:venue_addr")){
					try{
						event.setVenueAddress(property.getFirstChild().getNodeValue());
						Log.i(tag,"venue address"+(property.getFirstChild().getNodeValue()));
					}
					catch(Exception e){
						Log.i(tag, "No venue address");
					}		
				} else if (property.getNodeName().equals("description")){
					try{
						String desc = (property.getFirstChild().getNodeValue());
						TextUtils.htmlEncode(desc);
						System.out.println("description first:"+desc);
						desc=TextUtils.htmlEncode(desc);
						System.out.println("description second:"+desc);
						
						//event.setDescription(property.getFirstChild().getNodeValue());
						Log.i(tag,"desc"+(property.getFirstChild().getNodeValue()));
						Log.i(tag,"desc"+desc);
					}
					catch(Exception e){
						Log.i(tag, "No desc");
					}

				} else if (property.getNodeName().equals("ens1:img_link")){
					try{
						event.setImageLink(property.getFirstChild().getNodeValue());
						Log.i(tag,"img link"+(property.getFirstChild().getNodeValue()));
					}
					catch(Exception e){
						Log.i(tag, "No imagelink");
					}		
				} else if (property.getNodeName().equals("ens1:type")){
					try{
						event.setType(property.getFirstChild().getNodeValue());
						Log.i(tag,"type"+(property.getFirstChild().getNodeValue()));
					}
					catch(Exception e){
						Log.i(tag, "No type");
					}
				} else if (property.getNodeName().equals("ens1:org")){
					try{
						event.setOrganization(property.getFirstChild().getNodeValue());
						Log.i(tag,"org"+(property.getFirstChild().getNodeValue()));
					}
					catch(Exception e){
						Log.i(tag, "No Organization");
					}
				}

			}
		}

		if(checkDate(event.getsDate())=="today"){
			todayEvents.add(event);
			Log.i(tag, "Today Event:"+event.getsDate());
		}
		else if(checkDate(event.getsDate())=="tomorrow"){
			tomorrowEvents.add(event);
			Log.i(tag, "Tommorrow Event:"+event.getsDate());
		}
		else if(checkDate(event.getsDate())=="today\tomorrow"){
			tomorrowEvents.add(event);
			todayEvents.add(event);
			Log.i(tag, "Tommorrow Event:"+event.getsDate());
		}

		else{
			weekEvents.add(event);
			Log.i(tag, "Week Event:"+event.getsDate());
		}


		XmlParser.eventsList.add(event);
		//return (XmlParser.eventsNodeList.getLength()/8);
		return 1;

	}

	

	private static String checkDate(String getsDate) {
		Calendar calendar = Calendar.getInstance();

		Date date = null;
		String formattedDate = formatter.format(todaysDate);
		System.out.println("today new date:"+formattedDate);

		calendar.add(Calendar.DATE,0);

		date =  calendar.getTime();
		calendar.add(Calendar.DATE, 1);
		date = calendar.getTime();
		Date tomorrowDate = date;

		tomorrow = formatter.format(date);
		Date eventStartDate = null;
		Date eventEndDate = null;
		if(getsDate.contains("~")){
			try{
				String [] detailedDate = new String [2];
				detailedDate = getsDate.split("~");

				eventStartDate = df.parse(detailedDate[0]);            
				//System.out.println("Start = " + df.format(eventStartDate));
				eventEndDate = df.parse(detailedDate[1]);            
				//System.out.println("End = " + df.format(eventEndDate));
			}
			catch(Exception e){

			}
			if(todaysDate.equals(eventStartDate) || todaysDate.equals(eventEndDate)){
				//return("Either start or end day");
				return "today";
				
			}
			else if(todaysDate.after(eventStartDate)&& todaysDate.before(eventEndDate)){
				//return "its in the middle";
				if(eventStartDate.equals(tomorrow) || eventEndDate.equals(tomorrow))
					return "today\tomorrow";
				else if(tomorrowDate.after(eventStartDate)&& tomorrowDate.before(eventEndDate))
					return "today\tomorrow";
				
				return "today";
				
			}
			else if(eventStartDate.equals(tomorrow) || eventEndDate.equals(tomorrow))
				return "tomorrow";
			else if(tomorrowDate.after(eventStartDate) && tomorrowDate.before(eventEndDate)){
				return "tomorrow";
			}
			else
				return "its in the future";


		}

		else{
			
			System.out.println("tomorrow date:"+tomorrow.substring(0,10));
			System.out.println("event date:"+getsDate.substring(0,10));
			

			if(getsDate.substring(0, 10).equalsIgnoreCase(formattedDate.substring(0, 10))){
				System.out.println("Its today");
				return "today";
			}
			else if(getsDate.substring(0, 10).equalsIgnoreCase(tomorrow.substring(0, 10))){
				System.out.println("Its toomorrow");
				return "tomorrow";
			}
			return "future";

		}
	}

}
